package com.qiku.web.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "loginFilter2",urlPatterns = "/*")
public class LoginFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1 判断请求路径中是否是index
        HttpServletRequest req = (HttpServletRequest) request;
        // 获取请求路径
        String servletPath = req.getServletPath();
//        System.out.println("servletPath：" + servletPath);
        if (servletPath.contains("user")||servletPath.contains("resource")||servletPath.contains("collect")){
            // 2 是访问index.jsp  再判断登陆状态
            HttpSession session = req.getSession();
            String username = (String) session.getAttribute("username");
            ServletContext context = request.getServletContext();
            Map<String,String> userLoginMap = (Map<String, String>) context.getAttribute("userLoginMap");
            String sid01 = userLoginMap.get(username);
            String sid02 = session.getId();
            if (username != null && sid02.equals(sid01)){
                // 2.2 已登录  则 放行
                chain.doFilter(request,response);
            }else{
                // 2.1 未登录  则 重定向到登录页面
                ((HttpServletResponse) response).sendRedirect("login.jsp");
            }
        }else{
            // 3 不是访问index.jsp  放行即可
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
